<?php
/* 不能改成file，名字与lib/file.php库文件发生冲突 V1.3 */
class UploadfilesController extends AppController {
	var $name = 'Uploadfiles';
	var $helpers = array (
			'Html' 
	);

    var $components = array(
        'Acl',
        'Auth'=>array(
            'authenticate' => array(
                'Form'=>array(
                    'userModel' => 'Staff','recursive' => 1,
                    'fields'=>array(
                        'username'=>'name',
                        'password'=>'password'
                    )
                ),
            ),
            'authorize' => array(
                'all' => array(
                    'actionPath' => 'controllers/'
                ),
                'Crud',
            )
//         	'authorize' => 'Controller',
        ),'AclFilter','RequestHandler','Paginator',
        'TaskQueue','WordSegment','SwfUpload' ,
        'Email', 'Session', 'Hook'=>array(),
    );

	function beforeFilter() {
		// print_r($_POST);print_r($_COOKIE);print_r($_FILES);exit;
		// flash传输过来的，只使用session验证
		if (isset ( $_POST ['PHP_SESSION_ID'] ) && ! empty ( $_POST ['PHP_SESSION_ID'] )) {
			$this->Session->id ( $_POST ['PHP_SESSION_ID'] );
			$_COOKIE ['PHPSESSID'] = $_POST ['PHP_SESSION_ID'];
			$_COOKIE ['MIAOCMS'] ['Auth'] ['Staff'] = $_POST ['MIAOCMS'] ['Auth'] ['Staff'];
		}

		$this->autoRender = false;
		parent::beforeFilter ();
	}
	
	function admin_update() {
		if (! empty ( $this->data )) {
			if (isset ( $this->data ['Uploadfile'] ) && is_array ( $this->data ['Uploadfile'] )) {
				foreach ( $this->data ['Uploadfile'] as $fk => $file ) {
					$this->Uploadfile->create ();
					$fileinfo = array ();
					$fileinfo ['id'] = $file ['id'];
					$fileinfo ['name'] = $file ['name'];
					// print_r($fileinfo);
					$this->Uploadfile->save ( $fileinfo, true, array (
							'name' 
					) );
				}
			}
		}
	}


    public function admin_qn_token(){
        header("Access-Control-Allow-Origin: *");
        if( $this->currentUser['id'] ) {
            $token = CrawlUtility::qiniuToken(Configure::read('Qiniu.bucket'),null,false);
            if($token) {
                echo json_encode(array(
                    'ret'=>0,
                    'fops' => '',
                    'type' => 'qiniu',
                    'wartermark' => '',
                    'uid' => $this->currentUser['id'],
                    'token'=>$token,
                ));
                exit;
            }
            else{
                echo json_encode(array('ret'=>-1,'msg'=>'获取上传效验码出错'));
            }
        }
        else{
            echo json_encode(array('ret'=>-1,'msg'=>'请先登录'));
        }
        exit;
    }

	function admin_listfile($uploadmodel = 'Article', $listmodel = 'all', $field = 'ckeditor', $page = 1) {
		$this->autoRender = true;
		$this->set ( 'uploadmodel', $uploadmodel );
		$conditions = array ();
		if ($listmodel != 'all') {
			$conditions ['modelclass'] = $listmodel;
		}
		if ($field == 'ckeditor') {
			$conditions ['fieldname'] = 'ckeditor';
		}
		$pagenum = 20;
		$uploadfiles = $this->Uploadfile->find ( 'all', array (
				'conditions' => $conditions,
				'limit' => $pagenum,
				'page' => $page 
		) );
		$totalnum = $this->Uploadfile->find ( 'count', array (
				'conditions' => $conditions 
		) );
		
		$this->set ( 'uploadfiles', $uploadfiles );
		// print_r($uploadfiles);
		App::uses ( 'Page', 'Lib' );
		$pagelinks = new Page ( $totalnum, $pagenum, "/admin/uploadfiles/listfile/$uploadmodel/$listmodel/$field/", $page );
		$page_navi = $pagelinks->renderNav ( 10 );
		
		$this->set ( 'page_navi', $page_navi );
	}	
	/**
	 * 文件管理 for ckeditor
	 * 此页面不调用layout.
	 * 参考 https://github.com/simogeo/Filemanager
	 * 大量的个性化修改，无法复用升级
	 */
	function admin_filemanage(){
		$this->layout = null;
		App::import('Vendor', 'Filemanager', array('file' => 'filemanage'.DS.'filemanager.class.php'));
		$config = array();
		$config['culture'] = 'zh-cn';
		$config['date'] = 'd M Y H:i';
		$config['icons']['path'] = (APP_SUB_DIR).'/img/icons/fileicon/';
		$config['icons']['directory'] = '_Open.png';
		$config['icons']['default'] = 'default.png';
		$config['upload']['overwrite'] = false; // true or false; Check if filename exists. If false, index will be added
		$config['upload']['size'] = false; // integer or false; maximum file size in Mb; please note that every server has got a maximum file upload size as well.
		$config['upload']['imagesonly'] = false; // true or false; Only allow images (jpg, gif & png) upload?
		$config['images'] = array('jpg', 'jpeg','gif','png');
		$config['unallowed_files']= array('.htaccess','.php');
		$config['unallowed_dirs']= array();
		$config['doc_root'] = UPLOAD_FILE_PATH; // No end slash
		$config['plugin'] = null;
		$fm = new Filemanager($config);
		/* 无参数传入时,调用模板生成页面，此页面不调用layout. */
		if(!empty($_REQUEST['mode'])) {
			if(!empty($_GET['mode'])) {
				switch($_GET['mode']) {	
					case 'getinfo':		
						if($fm->getvar('path')) {
							$response = $fm->getinfo();
						}
						break;
					case 'getfiles':
						if($fm->getvar('path')) {
							$response = $fm->getfiles();
						}
						break;
					case 'getfolder':						 
						if($fm->getvar('path')) {
							$response = $fm->getfolder();
						}
						break;		
					case 'rename':		
						if($fm->getvar('old') && $fm->getvar('new')) {
							$response = $fm->rename();
						}
						break;		
					case 'delete':		
						if($fm->getvar('path')) {
							$response = $fm->delete();
						}
						break;
					case 'addfolder':		
						if($fm->getvar('path') && $fm->getvar('name')) {
							$response = $fm->addfolder();
						}
						break;		
					case 'download':
						if($fm->getvar('path')) {
							$fm->download();
						}
						break;
					case 'preview':
						if($fm->getvar('path')) {
							$fm->preview();
						}
						break;
					default:
						$fm->error($fm->lang('MODE_ERROR'));
						break;		
				}
		
			} else if(isset($_POST['mode']) && $_POST['mode']!='') {		
				switch($_POST['mode']) {
					case 'add':		
						if($fm->postvar('currentpath')) {
							$fm->add();
						}
						break;
					default:						
						$fm->error($fm->lang('MODE_ERROR'));
						break;
				}
		
			}
			echo json_encode($response);
			exit();
		}
	}
	
	public function admin_download($id){
		$fileinfo = $this->Uploadfile->findById($id);
		if(!empty($fileinfo)){
			$filename = $fileinfo['Uploadfile']['fspath'];
			header("Content-Type: application/force-download");
			header("Content-Disposition: attachment; filename=".basename($filename));
			echo file_get_contents(UPLOAD_FILE_PATH.$filename);
		}
		else{
			throw new NotFoundException(__('Error url,this url page is not exist.'));
		}
		exit;
	}
	
	function admin_uploadtest() {
		/* 无操作，仅调用admin_uploadtest模版，供开发测试使用*/
	}
	/**
	 * 保存swfupload上传的文件。
	 * 
	 * post值选项：
	 * 
	 * "no_db" : 1, //不保存到数据库，
	 * "no_thumb" : 1, // 不生成缩略图，
	 * "save_folder":'/', //传入要保存的目标文件夹，相对于webroot目录，
	 */
	function admin_upload() {
		/* $file_post_name 默认为upload，
		ckeditor传入的文件字段名为upload。但无$_POST ['file_post_name']
		*/
		$file_post_name = $_POST['file_post_name']?$_POST['file_post_name']:'upload';
		$info = array ();
		$info ['ret'] = -1;
		$info ['fieldname'] = $file_post_name;
		if (isset ( $this->params['form'] [$file_post_name] )) {
			// upload the file
			if(!empty($_REQUEST['no_thumb'])){ //图片不自动生成缩略图
				$this->SwfUpload->gen_thumb = false;
			}
			if(!empty($_REQUEST['save_folder'])){ //指定保存位置
				$this->SwfUpload->uploadpath = UPLOAD_FILE_PATH.$_POST['save_folder'];
			}
			elseif(!empty($_REQUEST['type'])){ //ckeditor传入了指定的类型，如images,flashes,videos
				$this->SwfUpload->setSavePath($_REQUEST['type']);
			}
			$this->SwfUpload->file_post_name = $file_post_name;
			if($_REQUEST['no_db']){
				$this->SwfUpload->gen_thumb = false;
			}
			
			if ( $fileifo = $this->SwfUpload->upload () ) {
				if($_REQUEST['no_db']){// 不保存到数据库，在ckeditor中上传文件的场景					
					$info ['ret'] = 0;
					$info =array_merge($info,$fileifo);
					
					if ( substr ( $fileifo['fspath'], 0, 7 ) != 'http://' ) {
					    $file_url = UPLOAD_FILE_URL.str_replace('//','/',$fileifo['fspath']);
					} else {
					    $file_url = $fileifo['fspath'];
					}

                    $info['fspath'] = $info['url'] = $file_url;
					
					if(is_image($file_url)){
						$info['message'] = '<a href="'.$file_url.'" title="'.__( 'Preview').'" target="_blank"><img src="'.$file_url.'" style="max-height:120px"/></a>';
					}
					else{
						$info['message'] = '<a href="'.$file_url.'" target="_blank">'.__( 'Preview').'</a>';
					}
				}
				else{
					$file_model_name = $_POST['file_model_name'];
					$modelname = Inflector::classify ( $this->name );
					$this->data [$modelname] ['modelclass'] = $file_model_name;
					$this->data [$modelname] ['fieldname'] = $file_post_name;
					$this->data [$modelname] ['name'] = $fileifo['filename'];
					$this->data [$modelname] ['size'] = $this->params ['form'] [$file_post_name] ['size'];
					$this->data [$modelname] ['fspath'] = $fileifo['fspath'];
					$this->data [$modelname] ['type'] = $fileifo['file_type'];
					if (empty($_REQUEST['no_thumb']) && 'image' == substr ($fileifo['file_type'], 0, 5 )) {
						$this->data [$modelname] ['thumb'] = $fileifo['thumb'];
						$this->data [$modelname] ['mid_thumb'] = $fileifo['mid_thumb'];
					}
					if (! ($file = $this->Uploadfile->save ( $this->data ))) {
						$this->Session->setFlash ( 'Database save failed' );
						$info ['message'] = $this->SwfUpload->filename . ' Database save failed'; // 保存记录时失败
					} else {
						$info ['ret'] = 0;
						$file_id = $this->Uploadfile->getLastInsertId ();

						$info ['fieldid'] = $fieldid = Inflector::camelize($file_model_name).Inflector::camelize($file_post_name);

						$info ['message'] = '<li class="upload-fileitem clearfix" id="upload-file-'.$file_id.'">';
						
						if (substr ( $this->data [$modelname] ['fspath'], 0, 7 ) != 'http://') {
							$file_url = UPLOAD_FILE_URL.str_replace ( '//', '/', ($this->data [$modelname] ['fspath']) );
						} else {
							$file_url = $this->data [$modelname] ['fspath'];
						}

                        $info['fspath'] = $info['url'] = $file_url;
						//$info ['message'] .= var_dump($this->SwfUpload,true).$this->data [$modelname] ['type'].'---'.$this->data [$modelname] ['thumb'];
						
						if ('image' == substr ( $this->data [$modelname] ['type'], 0, 5 )) {
							$info ['message'] .= '<img src="' . $file_url . '"/>';
						}
						$info ['message'] .= '<div class="form-group  form-inline"><input type="hidden" name="data[Uploadfile][' . $file_id . '][id]" value="' . $file_id . '">
						<p>
						<label>'.__ ( 'Uploadfile Name').'</label>: <input type="text" class="form-control" name="data[Uploadfile]['.$file_id.'][name]" style="width: 520px;" value="'.urldecode($this->SwfUpload->filename).'"/> &nbsp;
	        			<label>'.__ ( 'Sort Order').'</label>: <input style="width:60px;" class="form-control" type="text" name="data[Uploadfile]['.$file_id.'][sortorder]" value="0"/> &nbsp;
	        			<label>'.__ ( 'File Version').'</label>: <input style="width:60px;" type="text" name="data[Uploadfile]['.$file_id.'][version]" value=""/>
						</p>
	        			<div><label title="'.__('Used as image click url').'">'.__ ( 'Link url').'</label>: <input class="form-control" style="width: 520px;" max-size="200" placeholder="链接地址在200字符以内" type="text" name="data[Uploadfile]['.$file_id.'][link]" value=""/></div>
	        			
						<p><label>'.__ ( 'Uploadfile description').'</label>:<textarea class="form-control" name="data[Uploadfile]['.$file_id.'][description]" rows="1" cols="60"></textarea></p>
						</div>';
						
						// 使用 $this->request->webroot 连接在图片前面，而不用Router::url，避免后台添加图片时，文件都带上了 /manage/路径  
						
						if ('image' == substr ( $this->data [$modelname] ['type'], 0, 5 )) {
							$mid_thumb_url = str_replace ( '\\', '/', $this->data [$modelname] ['mid_thumb'] );
							$mid_thumb_url = UPLOAD_FILE_URL.str_replace ( '//', '/',$mid_thumb_url);
							if (substr ( $this->data [$modelname] ['fspath'], 0, 7 ) != 'http://') {
								$src_url = UPLOAD_FILE_URL.str_replace ( '//', '/', ($this->data [$modelname] ['fspath']) );
							} else {
								$src_url = $this->data[$modelname]['fspath'];
							}
							
							if(empty($mid_thumb_url)) {
							    $mid_thumb_url = $src_url;
							}
							
							
							$info ['message'] .= '<p>
							<a href="' . $src_url . '" target="_blank">' . __ ( 'Preview') . '</a>
			        		<a href="javascript:void(0);" onclick="insertHTML(\'&lt;img id=&#34;file_' . $file_id . '&#34; src=&#34;' . $mid_thumb_url . '&#34; >\')">' . __ ( 'Insert Editor') . '</a>
			        		
			        		<a class="upload-file-delete" rel="'.$file_id.'" href="#" data-url="' . Router::url ( '/admin/uploadfiles/delete/' . $file_id.'.json') . '">' . __ ( 'Delete') . '</a> 
			        		<a href="javascript:void(0);" onclick="setCoverImg(\'' . $this->data [$modelname] ['modelclass'] . '\',\'' . $mid_thumb_url . '\');">' . __ ( 'Set as title img') . '</a></p>
							
							';
						}
						$info ['message'] .= '</li>';
					}
				}
			} else {
				$info ['message'] = $this->SwfUpload->errorMessage;
				$this->Session->setFlash ( $this->SwfUpload->errorMessage );
			}
		} else {
			$info ['message'] = 'empty field name';
		}
		
		if($_REQUEST['return']=='ueditor'){
			echo json_encode(array(
					"state" => 'SUCCESS',
					"url" => $file_url,
					"title" => $info['filename'],
					"original" => $info['filename'],
					"type" => $info['file_type'],
					"size" => $this->params ['form'] [$file_post_name] ['size']
			));
		}
		elseif($_REQUEST['return']=='ckeditor'){
			$funcNum = $_REQUEST['CKEditorFuncNum'];
			
			if($info ['ret'] == 0){
				echo '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$funcNum.', "'.(UPLOAD_FILE_URL.$fileifo['fspath']).'", "");</script>';
			}
			else{
				echo '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$funcNum.', "", "'.$info ['message'].'");</script>';
			}
		}
		else{
			$result = json_encode ( $info );
			echo $result;
		}
		exit ();
	}
	
	public function admin_ueditor(){
	    $action = $_GET['action'];
	
	    header('Content-Type: application/x-javascript');

	    switch ($action) {
	        case 'config':
	            $result =  '{"imageActionName":"uploadimage","imageFieldName":"upload","imageMaxSize":2048000,"imageAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"imageCompressEnable":true,"imageCompressBorder":1600,"imageInsertAlign":"none","imageUrlPrefix":"","imagePathFormat":"\/ueditor\/php\/upload\/image\/{yyyy}{mm}{dd}\/{time}{rand:6}","scrawlActionName":"uploadscrawl","scrawlFieldName":"upload","scrawlPathFormat":"\/ueditor\/php\/upload\/image\/{yyyy}{mm}{dd}\/{time}{rand:6}","scrawlMaxSize":2048000,"scrawlUrlPrefix":"","scrawlInsertAlign":"none","snapscreenActionName":"uploadimage","snapscreenPathFormat":"\/ueditor\/php\/upload\/image\/{yyyy}{mm}{dd}\/{time}{rand:6}","snapscreenUrlPrefix":"","snapscreenInsertAlign":"none","catcherLocalDomain":["image3.135editor.com","image.135editor.com","image2.135editor.com","img.wx135.com","rdn.135editor.com","qdn.135editor.com","cdn.135editor.com","img.baidu.com"],"catcherActionName":"catchimage","catcherFieldName":"source","catcherPathFormat":"\/ueditor\/php\/upload\/image\/{yyyy}{mm}{dd}\/{time}{rand:6}","catcherUrlPrefix":"","catcherMaxSize":2048000,"catcherAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"videoActionName":"uploadvideo","videoFieldName":"upload","videoPathFormat":"\/ueditor\/php\/upload\/video\/{yyyy}{mm}{dd}\/{time}{rand:6}","videoUrlPrefix":"","videoMaxSize":2048000,"videoAllowFiles":[".flv",".swf",".mkv",".avi",".rm",".rmvb",".mpeg",".mpg",".ogg",".ogv",".mov",".wmv",".mp4",".webm",".mp3",".wav",".mid"],"fileActionName":"uploadfile","fileFieldName":"upload","filePathFormat":"\/ueditor\/php\/upload\/file\/{yyyy}{mm}{dd}\/{time}{rand:6}","fileUrlPrefix":"","fileMaxSize":2048000,"fileAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp",".flv",".swf",".mkv",".avi",".rm",".rmvb",".mpeg",".mpg",".ogg",".ogv",".mov",".wmv",".mp4",".webm",".mp3",".wav",".mid",".rar",".zip",".tar",".gz",".7z",".bz2",".cab",".iso",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".pdf",".txt",".md",".xml"],"imageManagerActionName":"listimage","imageManagerListPath":"\/ueditor\/php\/upload\/image\/","imageManagerListSize":20,"imageManagerUrlPrefix":"","imageManagerInsertAlign":"none","imageManagerAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"fileManagerActionName":"listfile","fileManagerListPath":"\/ueditor\/php\/upload\/file\/","fileManagerUrlPrefix":"","fileManagerListSize":20,"fileManagerAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp",".flv",".swf",".mkv",".avi",".rm",".rmvb",".mpeg",".mpg",".ogg",".ogv",".mov",".wmv",".mp4",".webm",".mp3",".wav",".mid",".rar",".zip",".tar",".gz",".7z",".bz2",".cab",".iso",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".pdf",".txt",".md",".xml"]}';
	            break;
	            /* 上传图片 */
	        case 'uploadimage':
	            $_REQUEST['type'] = 'images';
	            $_REQUEST['return'] = 'ueditor';
	            if( empty($_REQUEST['remote_type']) ) {
	                $_REQUEST['remote_type'] = 'wechatUploadimg';
	            }
	            //$_REQUEST['no_db'] = 0;
	            $_REQUEST['no_thumb'] = 1;
	            $result =  $this->admin_upload();
	            break;
	            /* 上传视频 */
	        case 'uploadvideo':
	            $_REQUEST['type'] = 'videos';
	            $_REQUEST['return'] = 'ueditor';
	            //$_REQUEST['no_db'] = 1;
	            $_REQUEST['no_thumb'] = 1;
	            $result =  $this->admin_upload();
	            break;
	            /* 上传涂鸦 */
	        case 'uploadscrawl':
	            /* 上传文件  */
	        case 'uploadfile':
	            $_REQUEST['return'] = 'ueditor';
	            //$_REQUEST['no_db'] = 0;
	            $_REQUEST['no_thumb'] = 1;
	            $_POST['file_model_name'] = 'ueditor';
	            $result =  $this->admin_upload();
	            break;
	            /* 抓取远程文件 */
	        case 'catchimage':
	            $source = $_POST['source'];
	            	            
	            $list = array();
	            App::uses('WeixinUtility', 'Utility');
	            App::uses('CrawlUtility', 'Utility');
	            foreach ($source as $imgUrl) {
	                if( strpos('mmbiz.qpic.cn',$imgUrl) !== false ) {//qpic转换成qlogo
	                    $url = str_replace(array('http://mmbiz.qpic.cn','https://mmbiz.qpic.cn'),'https://mmbiz.qlogo.cn',$imgUrl);
	                    array_push($list, array(
    	                    "state" => 'SUCCESS',
    	                    "url" => 'http://image2.135editor.com/cache/remote/'.base64_encode( $url ),
    	                    "source" => htmlspecialchars($imgUrl)
	                    ));
	                }
	                elseif( strpos('https://mmbiz.qlogo.cn',$imgUrl) !== false ){//qlogo的跳过
	                    
	                    array_push($list, array(
	                        "state" => 'SUCCESS',
	                        "url" => 'http://image2.135editor.com/cache/remote/'.base64_encode($imgUrl),
	                        "source" => htmlspecialchars($imgUrl)
	                    ));
	                    
	                    continue;
	                }
	                else{ // 其余同步到微信，OSS
	                    $filepath = CrawlUtility::saveImagesByUrl($imgUrl,$imgUrl);
	                    if($filepath) {
	                        array_push($list, array(
	                            "state" => 'SUCCESS',
	                            "url" => $filepath,
	                            "source" => htmlspecialchars($imgUrl)
	                        ));
	                        
	                        /*
	                         * $filepath = CrawlUtility::saveImagesByUrl($imgUrl,$imgUrl,array('oss'=>false,'resize'=>false));
	                         * WeixinUtility::$appId = Configure::read('Weixin.AppId'); //默认到服务号
	                         * $info = WeixinUtility::uploadImg( UPLOAD_FILE_PATH . $filepath);
	                        if($info['url']) {
	                            @unlink( UPLOAD_FILE_PATH . $filepath );//上传微信成功后，删除本地图片
	                            array_push($list, array(
    	                            "state" => 'SUCCESS',
    	                            "url" => 'http://image2.135editor.com/cache/remote/'.base64_encode($info["url"]),
    	                            "source" => htmlspecialchars($imgUrl)
	                            ));
	                        }
	                        else{ //上传至OSS服务器
	                            $md5_sum = md5($imgUrl); //使用md5码，忽略冲突
	                            $object_name = 'files/' . substr($md5_sum,0,2).'/'.substr($md5_sum,2,3) . '/'.$md5_sum.'.jpg';	                            
	                            $url = CrawlUtility::saveToAliOss($filepath,$object_name,true,false,false);	                            
	                            if( $url ) {
	                                array_push($list, array(
	                                    "state" => 'SUCCESS',
	                                    "url" => $url,
	                                    "source" => htmlspecialchars($imgUrl)
	                                ));
	                            }
	                        }*/
	                    }
	                }
	            }
	            /* 返回抓取数据 */
	            $result = json_encode(array(
	                'state'=> count($list) ? 'SUCCESS':'ERROR',
	                'list'=> $list
	            ));
	             
	            break;
	            /* 列出图片 */
	        case 'listimage':
	            $this->loadModel('EditorStyle');
	
	            $size = $_GET['size'] ? $_GET['size'] : 20;
	            $page = $_GET['start']/$size + 1;
	
	            $conditions = array('EditorStyle.cate_id >='=>50, 'EditorStyle.status' => 1 );
	            if($_GET['type'] == 'favor'){
	                $images = $this->EditorStyle->find('all',array(
	                    'conditions' => $conditions,
	                    'limit' => $size,
	                    'page' => $page,
	                    'joins' => array(array(
	                        'table' => 'favorites',
	                        'alias' => 'Favorite',
	                        'type' => 'inner',
	                        'conditions' => array('EditorStyle.id=Favorite.data_id','Favorite.model'=>'EditorStyle','Favorite.creator_id'=>$this->currentUser['id']),
	                    )),
	                ));
	
	                $total =  $this->EditorStyle->find('count',array(
	                    'conditions' => $conditions,
	                    'order' => 'recommend desc,sort desc',
	                    'recursive' => -1,
	                    'joins' => array(array(
	                        'table' => 'favorites',
	                        'alias' => 'Favorite',
	                        'type' => 'inner',
	                        'conditions' => array('EditorStyle.id=Favorite.data_id','Favorite.model'=>'EditorStyle','Favorite.creator_id'=>$this->currentUser['id']),
	                    )),
	                ));
	            }
	            else{
	                if($_GET['type'] == 'bg'){
	                    $conditions = array('EditorStyle.cate_id'=>51);
	                }
	                elseif($_GET['type'] == 'bggif'){
	                    $conditions = array('EditorStyle.cate_id'=>52);
	                }
	                elseif($_GET['type'] == 'split'){
	                    $conditions = array('EditorStyle.cate_id'=>53);
	                }
	                elseif($_GET['type'] == 'guide'){
	                    $conditions = array('EditorStyle.cate_id'=>56);
	                }
	                elseif($_GET['type'] == 'festival'){
	                    $conditions = array('EditorStyle.cate_id'=>54);
	                }
	                elseif($_GET['type'] == 'gif'){
	                    $conditions = array('EditorStyle.cate_id'=>55);
	                }
	                $images = $this->EditorStyle->find('all',array(
	                    'conditions' => $conditions,
	                    'limit' => $size,
	                    'page' => $page,
	                ));
	                	
	                $total =  $this->EditorStyle->find('count',array(
	                    'conditions' => $conditions,
	                    'order' => 'recommend desc,sort desc',
	                    'recursive' => -1,
	                ));
	            }
	
	            $result = array(
	                'state' => 'SUCCESS',
	                'list' => array(),
	                'start' => $_GET['start'],
	                'total' => $total,
	            );
	            foreach($images as $item){
	                $result['list'][] = array(
	                    'id'=> $item['EditorStyle']['id'],
	                    'title'=> $item['EditorStyle']['name'],
	                    'url'=> $item['EditorStyle']['coverimg'],
	                    'mtime'=>1400203383,
	                );
	            }
	            $result = json_encode($result);//'{"state":"SUCCESS","list":[{"url":"\/server\/ueditor\/upload\/image\/3 2.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/26.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/25.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/24.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/23.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/22.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/21.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/20.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/2.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/19.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/18.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/17.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/16.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/15.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/14.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/13.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/12.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/11.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/10.jpg","mtime":1400203383},{"url":"\/server\/ueditor\/upload\/image\/1.jpg","mtime":1400203383}],"start":"0","total":29}';
	            break;
	            /* 列出文件 */
	        case 'listfile':
	            break;
	            /* 抓取远程文件 */
	        case 'catchimage':
	            break;
	        default:
	            $result = json_encode(array(
	            'state'=> '请求地址出错'
	                ));
	                break;
	    }
	
	    /* 输出结果 */
	    if (isset($_GET["callback"])) {
	        if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
	            echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
	        } else {
	            echo json_encode(array(
	                'state'=> 'callback参数不合法'
	            ));
	        }
	    }
	    else{
	        echo $result;
	    }
	    exit;
	}
	
	function open($id) {
		$file = $this->get ( $id );
		if (isset ( $file )) {
			$this->redirect ( $file ['Uploadfile'] ['path'] . $file ['Uploadfile'] ['name'] );
			exit ();
		}
	}
	function admin_delete($id= NULL) {
		$file = $this->Uploadfile->findById ( $id );
		// 删除文件
		$this->SwfUpload->deletefile ( $file ['Uploadfile'] ['fspath'] );
		// 从数据库删除
		parent::admin_delete($id);
	}
	
	function get($id) {
		// get file info
		$file = $this->Uploadfile->findById ( $id );
		return $file;
	}
}
?>